package cn.gjculture.shopping.api.controller;

import cn.gjculture.shopping.api.service.WXService;
import cn.gjculture.shopping.api.util.MessageHandlerUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/wx")
@Slf4j
public class WXController {
    String token="wxApp";

    @Autowired
    WXService wxService;

    @GetMapping
    public String verify(String signature,String timestamp, String nonce, String echostr){
        log.info("signature:{}",signature);
        log.info("nonce:{}",nonce);
        log.info("timestamp:{}",timestamp);
        log.info("echostr:{}",echostr);
        List<String> list=new ArrayList<>();
        list.add(token);
        list.add(timestamp);
        list.add(nonce);
        Collections.sort(list);
        StringBuilder ss=new StringBuilder();
        for(String str:list){
            ss.append(str);
        }
        byte[] shaStr= DigestUtils.sha256(ss.toString());
        log.info("serverSignature:{}",new String(shaStr));
        signature.equals(new String(shaStr));
        return echostr;
    }


    @PostMapping
    public void acceptMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        log.info("微信请求进入...");
        Map<String,String> map = MessageHandlerUtil.parseXml(request);
        log.info("微信发送的消息是:{}", JSONObject.toJSONString(map));
        String  responseMessage = wxService.getAutoMessage(map);
        log.info("微信回复消息:{}",responseMessage);
        response.getWriter().println(responseMessage);
    }





}
